/*
* 计量单位模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");


// 查询计量单位列表
router.get('/list', (req, res) => {
    console.log("===========查询计量单位列表接口============");
    // 获取参数
    let {pageNum, pageSize, measureCode, measureName} = req.query;
    let sql = "select * from md_unit_measure";
    let sql_where = "";
    // 判断参数是否为空
    if(measureCode) {
        sql_where += ` where measure_code like '%${measureCode}%'`
    }
    if(measureName) {
        sql_where += ` ${measureCode ? "and" : "where"} measure_name = '${measureName}'`
    }
    // 分页查询
    sql_where += ` limit ${(pageNum - 1) * pageSize}, ${pageSize}`;
    sql += sql_where;
    
    // 查询数据库
    db.query("查询计量单位列表", sql, (err, result) => {
        if (err) {
            res.send({
                code: 500,
                msg: '查询计量单位列表失败'
            })
            return
        }
        // 查询总条数
        db.query("查询计量单位列表总条数", `select count(*) as total from md_unit_measure ${sql_where}`, (err, total) => {
            if (err) {
                res.send({code: 500, msg: '查询计量单位列表总条数失败'})
                return
            }
            if(result.length > 0) {
                // 变量Json数组key转成下划线第一个大写
                result = result.map(item => {
                    return toCamelCase(item)
                })
            }
            res.send({
                code: 200,
                msg: '查询成功',
                rows: result,
                total: total[0].total
            })
        })
        
    })
    
})

// 查询计量单位是否是主单位列表
router.get('/listprimary', (req, res) => {
    console.log("===========查询计量单位是否是主单位列表接口============");
    // 生成sql
    let sql = "select * from md_unit_measure where primary_flag = 'Y'";
    // 查询数据库
    db.query("查询计量单位是否是主单位列表", sql, (err, result) => {
        if (err) {
            res.send({
                code: 500,
                msg: '查询计量单位是否是主单位列表失败'
            })
            return
        }
        if(result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
        }
        res.send({
            code: 200,
            msg: '查询成功',
            data: result
        })
    })
})

// 新增计量单位
router.post('/', (req, res) => {
    console.log("===========新增计量单位接口============");
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取参数
    let {measureCode, measureName, primaryFlag, enableFlag, remark, changeRate, primaryId} = req.body;
    // 获取创建时间
    let createTime = moment().format('YYYY-MM-DD HH:mm:ss');
    // 生成sql
    let sql = `insert into md_unit_measure (measure_code, measure_name, primary_flag, enable_flag, remark, change_rate, primary_id, create_time, create_by) 
    values ('${measureCode}', '${measureName}', '${primaryFlag}', '${enableFlag}',  ${remark ? "'"+remark+"'"  :null}, ${changeRate ? "'"+changeRate+"'": null},
     ${primaryId ? "'"+primaryId+"'" : null}, '${createTime}', '${username}')`;
    
     // 查询单位编码和单位名称是否重复
    let sql_check = `select * from md_unit_measure where measure_code = '${measureCode}' or measure_name = '${measureName}'`;
    db.query("查询单位编码和单位名称是否重复", sql_check, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: '查询单位编码和单位名称是否重复失败'})
        }
        if(result.length > 0) {
            res.send({ code: 500, msg: '单位编码和单位名称不能重复'})
            return
        }
        // 查询数据库
        db.query("新增计量单位", sql, (err, result) => {
            if (err) {
                res.send({ code: 500, msg: '新增计量单位失败'})
                return
            }
            if(result.affectedRows > 0) {
                res.send({ code: 200, msg: '新增计量单位成功'})
            } else {
                res.send({ code: 500, msg: '新增计量单位失败'})
            }
        })
    })
    
})

// 编辑计量单位
router.put('/', (req, res) => {
    console.log("===========编辑计量单位接口============");
    // 获取编辑人
    let {username} = verifyToken(req.headers.authorization)
    // 获取参数
    let {measureCode, measureName, primaryFlag, enableFlag, remark, changeRate, primaryId, measureId} = req.body;
    // 获取更新时间
    let updateTime = moment().format('YYYY-MM-DD HH:mm:ss');
    // 判断单位编码和单位名称是否重复
    let sql_check = `select * from md_unit_measure where (measure_code = '${measureCode}' or measure_name = '${measureName}') and measure_id != ${measureId}`;
    db.query("查询单位编码和单位名称是否重复", sql_check, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: '查询单位编码和单位名称是否重复失败'})
            return
        }
        if(result.length > 0) {
            res.send({ code: 500, msg: '单位编码和单位名称不能重复'})
        }
        // 生成sql
        let sql = `update md_unit_measure set measure_code = '${measureCode}', measure_name = '${measureName}', primary_flag = '${primaryFlag}', enable_flag = '${enableFlag}',
         remark = ${remark ? "'"+remark+"'"  :null}, change_rate = ${changeRate ? "'"+changeRate+"'": null}, 
         primary_id = ${primaryId ? "'"+primaryId+"'" : null}, update_time = '${updateTime}', update_by = '${username}'  where measure_id = ${measureId}`
         // 更新数据库
         db.query("编辑计量单位", sql, (err, result) => {
             if (err) {
                res.send({ code: 500, msg: '编辑计量单位失败'})
                return
             }
             if(result.affectedRows > 0) {
                res.send({ code: 200, msg: '编辑计量单位成功'})
             }else{
                res.send({ code: 500, msg: '编辑计量单位失败'})
             }
         })
    })
})

// 删除计量单位
router.delete('/:id', (req, res) => {
    console.log("===========删除计量单位接口============");
    // 获取参数
    let {id} = req.params;
    // 生成sql
    let sql = `delete from md_unit_measure where measure_id  in(${id})`
    // 查询主单位是否被使用
    let sql_check = `select * from md_unit_measure where primary_id  in(${id})`
    db.query("查询主单位是否被使用", sql_check, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: '查询主单位是否被使用失败'})
            return
        }
        if(result.length > 0) {
            res.send({ code: 500, msg: '主单位被使用，不能删除'})
            return
        }
        // 删除数据库
        db.query("删除计量单位", sql, (err, result) => {
            if (err) {
                res.send({ code: 500, msg: '删除计量单位失败'})
                return
            }
            if(result.affectedRows > 0) {
                res.send({ code: 200, msg: '删除计量单位成功'})
            }else{
                res.send({ code: 500, msg: '删除计量单位失败'})
            }
        })
    })
})

// 查询单个计量单位
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个计量单位接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
    
    // 生成sql
    let sql = `select * from md_unit_measure where measure_id = ${id}`
    // 查询数据库
    db.query("查询单个计量单位", sql, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: '查询单个计量单位失败'})
            return
        }
        if(result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
        }
        res.send({ code: 200, msg: '查询单个计量单位成功', data: result[0]})
    })
})

// 查询计量单位选择启用列表
router.get("/selectall", async (req, res) => {
    console.log("===========查询计量单位选择启用列表接口============");
    // 生成sql
    let sql = `select * from md_unit_measure where enable_flag = "Y"`
    // 查询数据库
    db.query("查询计量单位选择启用列表", sql, (err, result) => {
        if (err) {
            res.send({ code: 500, msg: '查询计量单位选择启用列表失败'})
            return
        }
        if(result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
        }
        res.send({ code: 200, msg: '查询计量单位选择启用列表成功', data: result})
    })
})



module.exports = router;